<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/22 0022
 * Time: 下午 3:26
 */

namespace app\api\tool;


use app\common\service\Service;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\File;
use think\Request;

class Image
{
    private  $accessKey=null;
    private  $secretKey=null;
    private $bucket=null;
    private $code=null;
    private $message=null;
    private $service=null;
    public function __construct()
    {

        $this->accessKey=config("qiniu.access_key");
        $this->secretKey=config("qiniu.secret_key");
        $this->bucket=config("qiniu.bucket");//上传的空间
        $this->service=service('Image');

    }

    /**
     * 上传图片到七牛云存储
     * @param string $inputname
     * @return bool
     * @throws \Exception
     */
    public function upload($inputname='image'){

        // 构建鉴权对象
        $auth = new Auth($this->accessKey, $this->secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($this->bucket);
        $file=$_FILES[$inputname];

        // 要上传文件的本地路径
        $filePath = $file['tmp_name'];

        // 上传到七牛后保存的文件名
        $key = $this->getFileName($this->getExtension($file['name']));

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            $this->code=$err->code();
            $this->message=$err->message();
            log_error("上传图片","错误码:".$err->code().',提示：'.$err->message() );
            return false;
        } else {
            $image=[
                'type'=>3,
                'store_type'=>1
            ];
            $image['md5']=$ret['hash'];
            $image['uri']=$ret['key'];
            $image['note']=$file['name'];
            $image['ip']=Request::instance()->ip();
            $res=$this->service->add($image);
            return $res['id'];
        }
    }

    /**
     * 获取文件名
     * @param string $type
     * @param string $extension
     * @return string
     */
    private function getFileName($extension="jpg",$type='image'){
        $filename=$type.'_'.date('Y-m-d').'_'.uniqid().'.'.$extension;
        return $filename;
    }
    /*
     * 获取扩展名
     */
    private function getExtension($filename)
    {
        return substr($filename, strrpos($filename, '.')+1);
    }

    /**
     * 获取错误
     * @return null
     */
    private function getError(){
        return $this->message;
    }

    /**
     * get图片url
     */
    public function getImageUrl($image_id,$islogo=true){
        $image=$this->service->find($image_id);
        log_debug("获取图片",$image_id."{$image['uri']}" );
        if($image&&$image['store_type']==1){
            $url=config('qiniu.domain').$image['uri'];
            if($islogo){
                $url.='-logo';
            }
            return $url;
        }else{
            return false;
        }
    }
}